<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:file:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:file:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="queryParams.type === '107'">
        <el-select
          v-model="queryParams.codeId"
          placeholder="请选择"
          @change="gradeChange"
        >
          <el-option
            v-for="item in gradeList"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictCode"
          >
          </el-option>
        </el-select>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="章节名称" align="center" prop="chapterName" />
      <el-table-column label="文件名称" align="center" prop="name" />
      <el-table-column
        label="所属年级"
        align="center"
        prop="title"
        v-if="queryParams.type === '107'"
      />
      <el-table-column label="简介" align="center" prop="introduction" />
      <el-table-column
        label="文件排序"
        align="center"
        prop="sort"
        v-if="queryParams.type !== '107'"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:file:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:file:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            maxlength="140"
            :rows="5"
            placeholder="请输入文件简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件内容" prop="url">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="headers"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            name="file"
            :show-file-list="false"
            ref="upload"
          >
            <video v-if="fileUrl" :src="fileUrl" controls class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          v-if="queryParams.type === '107'"
          label="所属年级"
          prop="title"
        >
          <el-select v-model="form.codeId" placeholder="请选择">
            <el-option
              v-for="item in gradeList"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="显示排序"
          prop="sort"
          v-if="queryParams.type !== '107'"
        >
          <el-input-number
            v-model="form.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCalligraphy,
  getCalligraphy,
  addCalligraphy,
  updateCalligraphy,
  delCalligraphy,
  listBookFile,
  getBookFile,
  addBookFile,
  updateBookFile,
  delBookFile
} from "@/api/chapter/chapter";
import { listData } from "@/api/system/dict/data";
import { getToken } from "@/utils/auth";

export default {
  name: "enlightenmentData",
  data() {
    return {
      // 上传的图片服务器地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/upload/uploadFile",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {},
      fileUrl: "",
      gradeList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认"
        },
        {
          value: "primary",
          label: "主要"
        },
        {
          value: "success",
          label: "成功"
        },
        {
          value: "info",
          label: "信息"
        },
        {
          value: "warning",
          label: "警告"
        },
        {
          value: "danger",
          label: "危险"
        }
      ],
      // 状态数据字典
      statusOptions: [],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        parentId: undefined,
        type: undefined,
        chapterId: undefined,
        codeId: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.queryParams.parentId = this.$route.params.parenId;
    this.queryParams.type = this.$route.params.type;
    this.queryParams.chapterId = this.$route.params.chapterId;
    this.uploadData = {
      type: this.$route.params.type
    };
    this.getList();
  },
  methods: {
    /** 查询字典类型详细 */
    getList() {
      this.loading = true;
      if (this.queryParams.type !== "107") {
        listCalligraphy(this.queryParams).then(response => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        let params = {
          dictType: "grade_stage"
        };
        listData(params).then(res => {
          this.queryParams.codeId = this.queryParams.codeId
            ? this.queryParams.codeId
            : res.rows[0].dictCode;
          this.gradeList = res.rows;
          listBookFile(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        });
      }
    },
    /** 查询字典类型列表 */
    getTypeList() {
      listType().then(response => {
        this.typeOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.fileList = [];
    },
    // 表单重置
    reset() {
      if (this.queryParams.type !== "107") {
        this.form = {
          id: undefined,
          parentId: this.queryParams.parentId,
          type: this.$route.params.type,
          chapterId: this.$route.params.chapterId,
          codeId: undefined,
          name: undefined,
          introduction: undefined,
          url: undefined,
          sort: undefined
        };
      } else {
        this.form = {
          id: undefined,
          parentId: this.queryParams.parentId,
          type: this.$route.params.type,
          chapterId: this.$route.params.chapterId,
          codeId: this.queryParams.codeId,
          name: undefined,
          introduction: undefined,
          url: undefined,
          sort: undefined
        };
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.dictType = this.defaultDictType;
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fileUrl = "";
      this.open = true;
      this.title = "添加文件数据";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      if (this.queryParams.type !== "107") {
        getCalligraphy(id).then(response => {
          this.form = response.data;
          this.fileUrl = response.data.url;
          this.open = true;
          this.title = "修改文件数据";
        });
      } else {
        getBookFile(id).then(response => {
          this.form = response.data;
          this.fileUrl = response.data.url;
          this.open = true;
          this.title = "修改文件数据";
        });
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            if (this.queryParams.type !== "107") {
              updateCalligraphy(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              updateBookFile(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            if (this.queryParams.type !== "107") {
              addCalligraphy(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBookFile(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (this.queryParams.type !== "107") {
        this.$confirm(
          '是否确认删除文件名称为"' + row.name + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(function() {
            return delCalligraphy(row.id);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      } else {
        this.$confirm(
          '是否确认删除文件名称为"' + row.name + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(function() {
            return delBookFile(row.id);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    handleUploadSuccess(res, file) {
      this.fileUrl = res.url;
      this.form.url = res.url;
    },
    handleUploadError() {
      this.$message.error("视频插入失败");
    },
    beforefileUpload(file) {
      const isVIDEO = file.type === "video/mp4";
      const isLt2M = file.size / 1024 / 1024 / 1024 < 1;

      if (!isVIDEO) {
        this.$message.error("上传视频只能是 MP4 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传视频大小不能超过 1GB!");
      }
      return isVIDEO && isLt2M;
    },
    gradeChange(value) {
      this.queryParams.codeId = value;
      this.getList();
    }
  }
};
</script>
<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 192px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
::v-deep .avatar {
  width: 192px;
  height: 108px;
  display: block;
}
::v-deep .el-input--medium .el-input__inner {
  height: 28px;
  line-height: 28px;
}
::v-deep .el-input__suffix {
  top: 5px;
}
</style>
